package cs.uns.edu.ar.aygps.service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;

import cs.uns.edu.ar.aygps.db.ConnectionFactory;
import cs.uns.edu.ar.aygps.model.Tarjeta;
import cs.uns.edu.ar.aygps.model.exception.AyGPSException;

public class TarjetaService extends ModelService {
	
	private static HashMap<Integer, Tarjeta> tarjetas = new HashMap<Integer, Tarjeta>();

	public TarjetaService(String service) {
		super(service);
	}

	@Override
	public void executeService() throws AyGPSException {
		// TODO Auto-generated method stub

	}
	
	private static final String STORE_TARJETA= "INSERT INTO APP.TARJETA VALUES (? ,? )";
	public void storeTarjeta(Tarjeta t) {
		if(t!=null){
			Connection conn = null;
			try {
				conn = ConnectionFactory.getInstance().getConnection();
				PreparedStatement ps = conn.prepareStatement(STORE_TARJETA);
				ps.setInt(1, t.getNroTarjeta());
				ps.setString(2, t.getEmpresa());
				ps.execute();
				
				if (ps!=null)
					ps.close();
				tarjetas.put(t.getNroTarjeta(), t);				
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				try {
					if (conn!=null)
						conn.close();
				} catch (SQLException e) {
				}
			}
		}		
	}

	private static final String FIND_BY_NUMERO = "SELECT NROTARJETA,EMPRESA FROM APP.TARJETA WHERE NROTARJETA = ?" ;
	
	public Tarjeta getTarjetaByNumero(int nroTarjeta) {
		if (tarjetas.get(nroTarjeta)!=null){
			return tarjetas.get(nroTarjeta);
		}
		Connection conn = null;
		try {
			conn = ConnectionFactory.getInstance().getConnection();
			PreparedStatement ps = conn.prepareStatement(FIND_BY_NUMERO);
			ps.setInt(1, nroTarjeta);
			
			ResultSet rs = ps.executeQuery();
			Tarjeta t = null;
			while(rs.next()){
				t = new Tarjeta();
				t.setNroTarjeta(rs.getInt(1));
				t.setEmpresa(rs.getString(2));				
				tarjetas.put(t.getNroTarjeta(), t);
			}
			if (ps!=null)
				ps.close();
			return t;
		} catch (SQLException e) {

		} finally {
			try {
				if (conn!=null)
					conn.close();
			} catch (SQLException e) {
			}
		}
		return null;		
	}

}
